package com.castle.fortress.admin.jmreport.service.impl;

import cn.hutool.core.util.StrUtil;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.system.entity.SysRole;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.system.service.SysUserService;
import org.jeecg.modules.jmreport.api.JmReportTokenServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JmReportTokenServiceImpl implements JmReportTokenServiceI {
    @Autowired
    private SysUserService sysUserService;

    @Override
    public String getUsername(String s) {
        SysUser user = getSysUser(s);
        return user.getLoginName();
    }

    @Override
    public String[] getRoles(String s) {
        SysUser user = getSysUser(s);
        List<SysRole> roles =  user.getRoles();
        if(roles!=null){
            String[] strings = new String[roles.size()];
            for(int i=0;i<roles.size();i++){
                strings[i]= roles.get(i).getName();
            }
            return strings;
        }
        return new String[0];
    }

    /**
     * s 是用户ID
     * @param s
     * @return
     */
    @Override
    public Boolean verifyToken(String s) {
        return getSysUser(s)==null?false:true;
    }

    /**
     * 依据用户id获取用户信息
     * @param id
     * @return
     */
    private SysUser getSysUser(String id){
        SysUser user = null;
        if(StrUtil.isNotEmpty(id)){
            try {
                if("-1".equals(id)){
                    user = new SysUser();
                    user.setLoginName(GlobalConstants.SUPER_ADMIN_NAME);
                    user.setIsSuperAdmin(true);
                    user.setIsAdmin(true);
                }else{
                    user = sysUserService.getByIdExtends(Long.parseLong(id));
                }
            } catch (NumberFormatException e) {
                return user;
            }
        }
        return user;
    }

}
